﻿using SigowayCommonLib;
using SigowayCommonLib.ADO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WarehouseManager.Common;

namespace WarehouseManager
{
    public partial class LoginForm : Form
    {
        private DBManager dbManager;
        private bool existOperator = false;

        public LoginForm()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            this.txtID.Focus();
            this.dbManager = DBManager.GetDBManager();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtID.Text))
            {
                this.errorProvider.SetError(this.txtID, "请输入操作员ID");
                return;
            }

            //管理员登录
            if (isAdmin())
            {
                doLoginByAdmin();
                return;
            }

            if (String.IsNullOrEmpty(this.txtName.Text))
            {
                this.errorProvider.SetError(this.txtName, "请输入操作员姓名");
                return;
            }

            try
            {
                int result = -1;
                if (!this.existOperator)
                {
                    var sqlText = "INSERT INTO Operator VALUES(?,?,?,?,?,?,?)";

                    IDictionary<string, object> dicParameter = new Dictionary<string, object>();
                    dicParameter.Add("OperatorID", this.txtID.Text);
                    dicParameter.Add("OperatorName", this.txtName.Text);
                    dicParameter.Add("CreateUser", this.txtID.Text);
                    dicParameter.Add("CreateDate", DateTimeUtil.GetCurrentDate());
                    dicParameter.Add("UpdateUser", DBNull.Value);
                    dicParameter.Add("UpdateDate", DBNull.Value);
                    dicParameter.Add("Pwd", string.Empty);
                    result = this.dbManager.ExecuteNonQuery(new SQLObject(sqlText, dicParameter));
                }
                else
                {
                    result = 1;
                }

                if (result <= 0)
                {
                    MessageBoxHelp.ShowMsgError("登录失败！");
                    return;
                }

                BillCreateForm frmBillCreate = new BillCreateForm(this.txtID.Text, this.txtName.Text);
                frmBillCreate.CloseEvent = new Action(delegate ()
                {
                    this.Close();
                });
                frmBillCreate.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("登录失败!");
                LogManager.WriteLine("登录失败!Exception={0}", ex);
            }
        }

        private void doLoginByAdmin()
        {
            if (String.IsNullOrEmpty(this.txtPwd.Text))
            {
                this.errorProvider.SetError(this.txtPwd, "请输入管理员密码");
                return;
            }
            this.errorProvider.Clear();

            try
            {
                var sqlText = string.Format("SELECT OperatorName, Pwd FROM Operator WHERE OperatorID = '{0}'", this.txtID.Text);

                DataTable datUserInfo = this.dbManager.ExecuteQuery(new SQLObject(sqlText, null));
                string strPwd = string.Empty;
                string strName = string.Empty;

                if(datUserInfo != null && datUserInfo.Rows.Count > 0)
                {
                    strPwd = datUserInfo.Rows[0]["PWD"].ToString();
                    strName = datUserInfo.Rows[0]["OperatorName"].ToString();
                }

                if (this.txtPwd.Text != strPwd)
                {
                    MessageBoxHelp.ShowMsgInfor("您输入的管理员密码不正确，请重新输入！");
                    this.errorProvider.SetError(this.txtPwd, "您输入的管理员密码不正确");
                    this.txtPwd.Clear();
                    this.txtPwd.Focus();
                    return;
                }

                BillCreateForm frmBillCreate = new BillCreateForm(this.txtID.Text, strName);
                frmBillCreate.CloseEvent = new Action(delegate ()
                {
                    this.Close();
                });
                frmBillCreate.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("操作员信息查询失败!");
                LogManager.WriteLine("操作员信息查询失败!Exception={0}", ex);
            }
        }

        private void txtID_Validating(object sender, CancelEventArgs e)
        {
            this.lblMsg.Visible = false;
            this.errorProvider.Clear();

            //管理员
            if (isAdmin())
            {
                this.pnlPwd.Visible = true;
                this.txtPwd.Focus();
                return;
            }

            this.pnlPwd.Visible = false;

            try
            {
                var sqlText = string.Format("SELECT OperatorName FROM Operator WHERE OperatorID = '{0}'", this.txtID.Text);

                object objName = this.dbManager.GetSingleValue(new SQLObject(sqlText, null));
                if (objName != null)
                {
                    this.txtName.Text = objName.ToString();
                    this.txtName.Enabled = false;
                    this.existOperator = true;
                    this.btnLogin.Focus();
                }
                else
                {
                    this.lblMsg.Visible = true;
                    this.ClearName();
                    this.txtName.Focus();
                    this.existOperator = false;
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("操作员信息查询失败!");
                LogManager.WriteLine("操作员信息查询失败!Exception={0}", ex);
            }
        }

        private bool isAdmin()
        {
            return this.txtID.Text == ConstInfo.Admin;
        }

        private void ClearName()
        {
            this.txtName.Text = string.Empty;
            this.txtName.Enabled = true;
        }

        private void txtName_Validating(object sender, CancelEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtName.Text))
            {
                this.errorProvider.Clear();
            }
        }

        private void txtPwd_Validating(object sender, CancelEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtPwd.Text))
            {
                this.errorProvider.Clear();
            }

            this.btnLogin.Focus();
        }
    }
}
